package com.by.datasource.transaction;

import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.concurrent.Executor;

/**
 * 事务提交之后执行
 *
 * @author YanBingHao
 * @since 2025/9/29
 */
@Slf4j
public class AfterCommitExecutor {

    /**
     * 在事务提交后同步执行
     *
     * @param runnable
     */
    public static void execute(Runnable runnable) {
        if (!TransactionSynchronizationManager.isSynchronizationActive()) {
            runnable.run();
            return;
        }
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                runnable.run();
            }
        });
    }

    /**
     * 在事务提交后异步执行
     *
     * @param runnable
     */
    public static void execute(Runnable runnable, Executor executor) {
        if (!TransactionSynchronizationManager.isSynchronizationActive()) {
            executor.execute(runnable);
            return;
        }

        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                executor.execute(runnable);
            }
        });
    }


}
